<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { InventoryReport } from '@/service/api/inventory';
import SvgIcon from '@/components/custom/svg-icon.vue';

interface SalesItem {
  name: string;
  realNum: number;
  packingUnit: string;
  realMoney: number;
  percent: number;
  status: string;
}

const dataList = ref<SalesItem[]>([]);
const loading = ref(false);

// 获取销售分析数据
async function getSalesData() {
  loading.value = true;

  try {
    // 使用全局DateUtil计算当月的起始和结束日期
    const startOfMonth = DateUtil.startOfMonth();
    const endOfMonth = DateUtil.endOfMonth();

    const startDate = startOfMonth.format('YYYY-MM-DD');
    const endDate = endOfMonth.format('YYYY-MM-DD');

    const response = await InventoryReport.getSellBuyAnaByGood({
      startDate,
      endDate,
      stock: {},
      typeDesc: '根据商品分',
      orderDesc: '销售金额（降序）',
      typeType: 0
    });

    if (response && !response.error && response.data) {
      // 检查API响应数据结构（直接从response.data获取）
      const result = response.data;

      // transformBackendResponse已经提取了data，直接使用
      let salesData = null;

      if (result && result.totalDet) {
        salesData = result.data || result;
      } else if (result.data) {
        // 简化格式: {code: 1, data: [...]}
        salesData = result.data;
      } else if (Array.isArray(result)) {
        // 直接返回数据数组
        salesData = result;
      } else if (result && typeof result === 'object' && Object.keys(result).length > 0) {
        // 直接返回数据对象
        salesData = result;
      }

      if (salesData) {
        const salesList: SalesItem[] = [];

        // 处理对象格式数据 {key: {name, realNum, ...}}
        if (typeof salesData === 'object' && !Array.isArray(salesData)) {
          for (const key in salesData) {
            const item = salesData[key];
            if (item && typeof item === 'object') {
              salesList.push({
                name: item.name || '未知商品',
                realNum: item.realNum || 0,
                packingUnit: item.packingUnit || '件',
                realMoney: item.realMoney || 0,
                percent: item.percent || 0,
                status: getSalesItemStatus(Number.parseInt(key) || salesList.length)
              });
            }
          }
        }
        // 处理数组格式数据
        else if (Array.isArray(salesData)) {
          salesData.forEach((item: any, index: number) => {
            if (item && typeof item === 'object') {
              salesList.push({
                name: item.name || '未知商品',
                realNum: item.realNum || 0,
                packingUnit: item.packingUnit || '件',
                realMoney: item.realMoney || 0,
                percent: item.percent || 0,
                status: getSalesItemStatus(index)
              });
            }
          });
        }

        dataList.value = salesList;
      } else {
        showEmptyAnalysisList();
      }
    } else {
      showEmptyAnalysisList();
    }
  } catch (error) {
    // 错误处理 - 在生产环境中可以添加用户友好的提示
    showEmptyAnalysisList();
  } finally {
    loading.value = false;
  }
}

// 获取销售项目状态
function getSalesItemStatus(index: number): string {
  if (index === 0) return 'warning';
  if (index === 1) return 'exception';
  if (index === 2) return 'success';
  return 'primary';
}

// 显示空列表
function showEmptyAnalysisList() {
  dataList.value = [];
}

// 获取进度条颜色
function getProgressColor(percent: number, index: number): string {
  const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#eb2f96'];
  return colors[index % colors.length];
}

onMounted(() => {
  getSalesData();
});
</script>

<template>
  <div class="h-full flex flex-col">
    <!-- 标题 -->
    <div class="px-3 pb-2 pt-3">
      <div class="text-sm text-gray-700 font-medium">销售分析-按商品（本月）</div>
    </div>

    <!-- 内容区域 -->
    <div class="sales-scroll-container px-3" style="height: 200px; overflow-y: auto">
      <div v-if="loading" class="h-40 flex items-center justify-center">
        <NSpin size="small" />
      </div>

      <div v-else-if="dataList.length > 0" class="space-y-2">
        <div
          v-for="(item, index) in dataList"
          :key="index"
          class="rounded-lg bg-gray-50 p-2 transition-colors hover:bg-gray-100"
        >
          <!-- 商品信息头部 -->
          <div class="mb-1 flex items-center justify-between">
            <div class="text-sm text-gray-900 font-medium">{{ item.name }}</div>
            <div class="flex items-center text-xs text-gray-600 space-x-2">
              <span>销量：</span>
              <span class="text-blue-600 font-medium">{{ item.realNum }}</span>
              <span>{{ item.packingUnit }},</span>
              <span>销售金额：</span>
              <span class="text-green-600 font-medium">￥{{ item.realMoney.toLocaleString() }}</span>
            </div>
          </div>

          <!-- 进度条 -->
          <div class="flex items-center">
            <div class="mr-2 w-16 text-xs text-gray-500">金额占比：</div>
            <div class="flex-1">
              <NProgress
                :percentage="item.percent"
                :color="getProgressColor(item.percent, index)"
                :height="12"
                :show-indicator="true"
                indicator-placement="inside"
                class="w-full"
              />
            </div>
          </div>
        </div>
      </div>

      <div v-else class="h-40 flex items-center justify-center">
        <div class="text-center text-gray-400">
          <div class="mb-2 flex justify-center">
            <SvgIcon icon="mdi:chart-line" class="text-3xl" />
          </div>
          <div class="text-sm">暂无销售数据</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.sales-scroll-container {
  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #d1d5db #f9fafb;
}

.sales-scroll-container::-webkit-scrollbar {
  width: 6px;
}

.sales-scroll-container::-webkit-scrollbar-track {
  background: #f9fafb;
  border-radius: 3px;
}

.sales-scroll-container::-webkit-scrollbar-thumb {
  background: #d1d5db;
  border-radius: 3px;
}

.sales-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}

:deep(.n-progress-text) {
  font-size: 10px !important;
  color: #666;
}

:deep(.n-progress-rail) {
  border-radius: 4px;
  background-color: #f0f0f0;
}

:deep(.n-progress-fill) {
  border-radius: 4px;
}
</style>
